﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.CoreBusinessLogic.TenderAnalysis;
using SCMS.CoreBusinessLogic.Web;
using SCMS.Model;
using SCMS.UI.Models;
using SCMS.UI.GeneralHelper;
using SCMS.CoreBusinessLogic.Security;
using SCMS.CoreBusinessLogic.ActionFilters;
using SCMS.CoreBusinessLogic.StaffServices;
using SCMS.CoreBusinessLogic.NotificationsManager;
using SCMS.CoreBusinessLogic.OrderRequest;
using SCMS.CoreBusinessLogic._Supplier;
using SCMS.Resource;

namespace SCMS.UI.Controllers
{
    [MyException]
    public class TenderAnalysisController : PortalBaseController
    {
        private ITAnalysisService taService;
        private IStaffService staffService;
        private INotificationService notificationService;
        private IOrderRequest orService;
        private ISupplierService supplierService;

        public TenderAnalysisController(IPermissionService permissionService, IUserContext uc, ITAnalysisService tAervice, INotificationService notificationService,
            IOrderRequest orService, IStaffService staffService, ISupplierService supplierService)
            : base(uc, permissionService)
        {
            this.taService = tAervice;
            this.staffService = staffService;
            this.notificationService = notificationService;
            this.orService = orService;
            this.supplierService = supplierService;
        }

        #region .TA Actions.

        //
        // GET: /TenderAnalysis/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult LoadORDetails()
        {
            try
            {
                return PopulateORDetails();
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return View();
            }
        }

        private ActionResult PopulateORDetails()
        {
            using (var db = new SCMSEntities())
            {
                TAORequest tanalysis = new Models.TAORequest()
                {
                    EntityTenderAnalysis = new TenderAnalysi(),
                    OrderRequests = new SelectList(taService.GetOrderRequests(countryProg.Id), "Id", "RefNumber"),
                    TenderAnalisysNo = string.Format("--{0}--", Resources.Global_String_NewTAE), 
                    TADate = DateTime.Now.Date,
                    EditMode = false,
                    SupplierAdded = false
                };
                return View(tanalysis);
            }
        }

        public ActionResult LoadTADetailz(TAORequest entity)
        {
            try
            {
                entity.EntityTenderAnalysis.PreparedOn = DateTime.Now;
                using (var context = SCMSEntities.Define())
                {
                    entity.EntityTenderAnalysis.CountryProgrammeId = countryProg.Id;
                    entity.EntityTenderAnalysis.PreparedBy = currentStaff.Id;
                    entity.EntityTenderAnalysis.IsSubmitted = false;
                    taService.SaveTAnalysis(entity.EntityTenderAnalysis);
                    return SelectItems(entity.EntityTenderAnalysis.Id);
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return PopulateORDetails();
            }

        }

        public ActionResult BackToSelectItems(Guid id)
        {

            return SelectItems(id);
        }

        private ActionResult PopulateTADetails(Guid id)
        {
            return PopulateTADetailsFrank(id);
        }

        public ActionResult SelectItems(Guid id)
        {
            try
            {
                Models.SelectItemsToConsider ItemList = new SelectItemsToConsider();
                Models.ORItemList item;
                Model.TenderAnalysi ta = taService.GetTenderAnalysisEntity(id);
                Model.TenderBidder TBObject = new TenderBidder();
                List<Models.ORItemList> itemlist = new List<ORItemList>();
                List<Models.OtherItemList> OtherItemList = new List<Models.OtherItemList>();
                List<Model.OrderRequestItem> ORlist = taService.GetUnprocessedORItems(ta.OrderRequestId);
                foreach (OrderRequestItem ORitem in ORlist)
                {
                    item = new ORItemList();
                    item.EntityORItem = ORitem;
                    itemlist.Add(item);
                }
                ItemList.EntityORItems = itemlist;

                InitOtherItemsList(OtherItemList);
                ItemList.OtherItems = OtherItemList;

                ViewBag.TAID = id;
                return View("SelectItems", ItemList);
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return PopulateORDetails();
            }
        }

        private static void InitOtherItemsList(List<Models.OtherItemList> OtherItemList)
        {
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.GoodsReceivedNote_LoadGRNVerifyItems_DeliveryDate });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.Global_String_TransportCost });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.TenderAnalysis_String_Warranty });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.Global_String_Other });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.Global_String_ShippingTerms });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.Global_String_PaymentTerms });
        }

        private static void InitOtherItemsList(List<Models.OtherItemList> OtherItemList, TenderBidder tb)
        {
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.GoodsReceivedNote_LoadGRNVerifyItems_DeliveryDate, AddTOList = tb.DeliveryTime != null });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.Global_String_TransportCost, AddTOList = true });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.TenderAnalysis_String_Warranty, AddTOList = tb.Warranty != null });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.Global_String_Other, AddTOList = tb.Comments != null });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.Global_String_ShippingTerms, AddTOList = tb.ShippingTermId != null });
            OtherItemList.Add(new Models.OtherItemList() { Name = Resources.Global_String_PaymentTerms, AddTOList = tb.PaymentTermId != null });
        }

        public ActionResult GetSelectedItems(Guid id, SelectItemsToConsider Items)
        {
            try
            {
                Items.TAID = id;
                UserSession.CurrentSession.SSItems = Items;
                return GettselectedIttems(UserSession.CurrentSession.SSItems, false);
            }
            catch (Exception ex)
            {
                ViewBag.TAID = id;
                ViewBag.Message = ex.Message;
                return View(Items);
            }
        }

        public ActionResult LoadAddSupplier(Guid id, Guid? supplierId = null)
        {
            try
            {
                SelectItemsToConsider Items = UserSession.CurrentSession.SSItems;
                Models.GetSelectedItems model = new GetSelectedItems();
                DisplaySelectedItems Itemselected;
                OtherSelectedListItems otherListItmz;
                DisplayOtherSelectedItems OtherNoneList;
                List<DisplaySelectedItems> OrderRequestItems = new List<DisplaySelectedItems>();
                List<OtherSelectedListItems> OtherLIstItems = new List<OtherSelectedListItems>();
                List<DisplayOtherSelectedItems> OtherNoneLIstItems = new List<DisplayOtherSelectedItems>();
                model.Suppliers = new SelectList(taService.GetSuppliers(id, countryProg.Id), "Id", "Name");
                
                foreach (Models.ORItemList item in Items.EntityORItems)
                {
                    if (item.AddToList)
                    {
                        Itemselected = new DisplaySelectedItems();
                        Itemselected.EntityTBQuote = new TenderBidderQuote();
                        Itemselected.EntityTBQuote.OrderRequestItemId = item.ORItemID;
                        Itemselected.ItemName = taService.GetItemName(item.ORItemID).Name;
                        OrderRequestItems.Add(Itemselected);
                    }
                }
                model.Itemselected = OrderRequestItems;
                foreach (Models.OtherItemList item in Items.OtherItems)
                {
                    if (item.AddTOList)
                    {
                        if (item.Name == Resources.Global_String_ShippingTerms)
                        {
                            otherListItmz = new OtherSelectedListItems();
                            otherListItmz.ItemsList = new SelectList(taService.GetShippingTerms(countryProg.Id), "Id", "Description");
                            otherListItmz.ItemName = item.Name;
                            OtherLIstItems.Add(otherListItmz);
                        }
                        else if (item.Name == Resources.Global_String_PaymentTerms)
                        {
                            otherListItmz = new OtherSelectedListItems();
                            otherListItmz.ItemsList = new SelectList(taService.GetPaymentTerms(countryProg.Id), "Id", "Description");
                            otherListItmz.ItemName = item.Name;
                            OtherLIstItems.Add(otherListItmz);
                        }
                        else
                        {
                            OtherNoneList = new DisplayOtherSelectedItems();
                            OtherNoneList.ItemName = item.Name;
                            OtherNoneLIstItems.Add(OtherNoneList);
                        }
                    }
                }

                model.OtherNoneListItems = OtherNoneLIstItems;
                model.OtherListItemsz = OtherLIstItems;
                model.EntityTenderBidder = new TenderBidder();
                if (supplierId.HasValue)
                    model.SupplierID = supplierId.Value;
                model.TAid = Items.TAID;
                ViewBag.TAID = Items.TAID;
                model.IsSupplierSaved = false;
                model.UserMessage = "";
                return View("AddSupplier", model);
            }
            catch (Exception ex)
            {
                return GettselectedIttems(UserSession.CurrentSession.SSItems, false, ex.Message);
            }

        }

        public ActionResult AddSuppliers(Guid id, AddTAnalysis entity)
        {
            try
            {
                List<Model.TenderBidderQuote> TBQuotes = new List<TenderBidderQuote>();
                Model.TenderBidderQuote entityTBQuote = new Model.TenderBidderQuote();
                decimal totalcost = 0; Guid tbderid = Guid.NewGuid();
                foreach (RequestItems item in entity.RequestItems)
                {
                    entityTBQuote.Id = Guid.NewGuid();
                    entityTBQuote.UnitPrice = item.UnitCost;
                    entityTBQuote.OrderRequestItemId = item.ORItemId;
                    entityTBQuote.TenderBidderId = tbderid;
                    totalcost += item.UnitCost;
                    TBQuotes.Add(entityTBQuote);
                }
                totalcost += (decimal)entity.EntityTenderBidder.TransportCost;
                entity.EntityTenderBidder.TenderAnalysisId = id;
                entity.EntityTenderBidder.TotalCost = totalcost;
                entity.EntityTenderBidder.Id = tbderid;
                taService.SaveTBidder(entity.EntityTenderBidder, TBQuotes);
                return PopulateTADetails(id);
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return PopulateTADetails(Guid.Empty);
            }
        }

        public ActionResult DeleteSupplier(Guid id)
        {

            if (taService.DeleteTenderBidder(id))
            {
                return GettselectedIttems(UserSession.CurrentSession.SSItems, true, Resources.TenderAnalysisController_String_SupplierRemoved);
            }

            return GettselectedIttems(UserSession.CurrentSession.SSItems, false, "");
        }

        public ActionResult EditSupplier(Guid id)
        {
            try
            {
                SelectItemsToConsider Items = UserSession.CurrentSession.SSItems;
                Models.GetSelectedItems model = new GetSelectedItems();
                DisplaySelectedItems Itemselected;
                OtherSelectedListItems otherListItmz;
                DisplayOtherSelectedItems OtherNoneList;
                List<DisplaySelectedItems> OrderRequestItems = new List<DisplaySelectedItems>();
                List<OtherSelectedListItems> OtherLIstItems = new List<OtherSelectedListItems>();
                List<DisplayOtherSelectedItems> OtherNoneLIstItems = new List<DisplayOtherSelectedItems>();
                model.EntityTenderBidder = taService.GetTenderBidderById(id);
                model.Suppliers = new SelectList(taService.GetSuppliers(Items.TAID, countryProg.Id, model.EntityTenderBidder.Id), "Id", "Name", model.EntityTenderBidder.SupplierId);

                foreach (Models.ORItemList item in Items.EntityORItems)
                {
                    if (item.AddToList)
                    {
                        Itemselected = new DisplaySelectedItems();
                        Itemselected.EntityTBQuote = taService.GetTenderBidderQuoteByItemId(model.EntityTenderBidder.Id, item.ORItemID);
                        Itemselected.ItemName = taService.GetItemName(item.ORItemID).Name;
                        OrderRequestItems.Add(Itemselected);
                    }
                }
                model.Itemselected = OrderRequestItems;
                foreach (Models.OtherItemList item in Items.OtherItems)
                {
                    if (item.AddTOList)
                    {
                        if (item.Name == Resources.Global_String_ShippingTerms)
                        {
                            otherListItmz = new OtherSelectedListItems();
                            otherListItmz.ItemsList = new SelectList(taService.GetShippingTerms(countryProg.Id), "Id", "Description", model.EntityTenderBidder.ShippingTermId);
                            otherListItmz.ItemName = item.Name;
                            OtherLIstItems.Add(otherListItmz);
                        }
                        else if (item.Name == Resources.Global_String_PaymentTerms)
                        {
                            otherListItmz = new OtherSelectedListItems();
                            otherListItmz.ItemsList = new SelectList(taService.GetPaymentTerms(countryProg.Id), "Id", "Description", model.EntityTenderBidder.PaymentTermId);
                            otherListItmz.ItemName = item.Name;
                            OtherLIstItems.Add(otherListItmz);
                        }
                        else
                        {
                            OtherNoneList = new DisplayOtherSelectedItems();
                            OtherNoneList.ItemName = item.Name;
                            OtherNoneLIstItems.Add(OtherNoneList);
                        }
                    }
                }

                model.OtherNoneListItems = OtherNoneLIstItems;
                model.OtherListItemsz = OtherLIstItems;
                model.TAid = Items.TAID;

                foreach (DisplayOtherSelectedItems item in model.OtherNoneListItems)
                {
                    if (item.ItemName == Resources.GoodsReceivedNote_LoadGRNVerifyItems_DeliveryDate)
                    {
                        item.DeliveryDate = model.EntityTenderBidder.DeliveryTime;
                    }
                    else if (item.ItemName == Resources.Global_String_TransportCost)
                    {
                        item.UnitCost = (decimal)model.EntityTenderBidder.TransportCost;
                    }
                    else if (item.ItemName == Resources.TenderAnalysis_String_Warranty)
                    {
                        item.ItemValue = model.EntityTenderBidder.Warranty;
                    }
                    else if (item.ItemName == Resources.Global_String_Other)
                    {
                        item.ItemValue = model.EntityTenderBidder.Comments;
                    }
                }
                //PopulateSupplierDetails(model);
                ViewBag.TAID = Items.TAID;
                model.IsSupplierSaved = false;
                model.UserMessage = "";
                return View("AddSupplier", model);
            }
            catch (Exception ex)
            {
                return GettselectedIttems(UserSession.CurrentSession.SSItems, false, ex.Message);
            }
        }

        public ActionResult AddSupplier(Guid id, GetSelectedItems entity)
        {
            try
            {
                List<Model.TenderBidderQuote> TBQuotes = new List<TenderBidderQuote>();
                Model.TenderBidderQuote entityTBQuote;
                decimal totalcost = 0; Guid tbderid = Guid.NewGuid();
                OrderRequestItem orItem;
                foreach (DisplaySelectedItems item in entity.Itemselected)
                {
                    entityTBQuote = new Model.TenderBidderQuote();
                    entityTBQuote.Id = Guid.NewGuid();
                    entityTBQuote.UnitPrice = item.EntityTBQuote.UnitPrice;
                    entityTBQuote.OrderRequestItemId = item.EntityTBQuote.OrderRequestItemId;
                    orItem = orService.GetOrderRequestItemById(item.EntityTBQuote.OrderRequestItemId);                    
                    totalcost += (item.UnitCost * orItem.Quantity);

                    entityTBQuote.TenderBidderId = tbderid;
                    TBQuotes.Add(entityTBQuote);
                }
                entity.EntityTenderBidder.TenderAnalysisId = id;
                entity.EntityTenderBidder.Id = tbderid;
                if (entity.OtherNoneListItems != null)
                {
                    foreach (DisplayOtherSelectedItems item in entity.OtherNoneListItems)
                    {
                        if (item.ItemName == Resources.GoodsReceivedNote_LoadGRNVerifyItems_DeliveryDate)
                            entity.EntityTenderBidder.DeliveryTime = item.DeliveryDate;
                        else if (item.ItemName == Resources.Global_String_TransportCost)
                        {
                            entity.EntityTenderBidder.TransportCost = item.UnitCost;
                            totalcost += item.UnitCost;
                        }
                        else if (item.ItemName == Resources.TenderAnalysis_String_Warranty)
                        {
                            entity.EntityTenderBidder.Warranty = item.ItemValue;
                        }
                        else
                        {
                            entity.EntityTenderBidder.Comments = item.ItemValue;
                        }
                    }
                }
                if (entity.OtherListItemsz != null)
                {
                    foreach (OtherSelectedListItems item in entity.OtherListItemsz)
                    {
                        if (item.ItemName == Resources.Global_String_ShippingTerms)
                        {
                            entity.EntityTenderBidder.ShippingTermId = item.ItemID;
                        }
                        else if (item.ItemName == Resources.Global_String_PaymentTerms)
                        {
                            entity.EntityTenderBidder.PaymentTermId = item.ItemID;
                        }
                    }
                }
                entity.EntityTenderBidder.TotalCost = totalcost;
                if (taService.SaveTBidder(entity.EntityTenderBidder, TBQuotes))
                {
                    return GettselectedIttems(UserSession.CurrentSession.SSItems, true, Resources.TenderAnalysisController_String_NewSupplierAdded);
                }
                else
                    return GettselectedIttems(UserSession.CurrentSession.SSItems, false, Resources.Global_String_AnErrorOccurred);
            }
            catch (Exception ex)
            {
                return GettselectedIttems(UserSession.CurrentSession.SSItems, false, ex.Message);
            }
        }

        private ActionResult GettselectedIttems(SelectItemsToConsider Items, bool isSaved, string message = "")
        {
            Models.GetSelectedItems model = new GetSelectedItems();
            DisplaySelectedItems Itemselected;
            OtherSelectedListItems otherListItmz;
            DisplayOtherSelectedItems OtherNoneList;
            List<DisplaySelectedItems> OrderRequestItems = new List<DisplaySelectedItems>();
            List<OtherSelectedListItems> OtherLIstItems = new List<OtherSelectedListItems>();
            List<DisplayOtherSelectedItems> OtherNoneLIstItems = new List<DisplayOtherSelectedItems>();
            model.EntityTenderBidder = new TenderBidder();
            model.Suppliers = new SelectList(taService.GetSuppliers(Items.TAID, countryProg.Id), "Id", "Name");

            foreach (Models.ORItemList item in Items.EntityORItems)
            {
                if (item.AddToList)
                {
                    Itemselected = new DisplaySelectedItems();
                    Itemselected.EntityTBQuote = new TenderBidderQuote();
                    Itemselected.EntityTBQuote.OrderRequestItemId = item.ORItemID;
                    Itemselected.ItemName = taService.GetItemName(item.ORItemID).Name;
                    OrderRequestItems.Add(Itemselected);
                }
            }
            model.Itemselected = OrderRequestItems;
            foreach (Models.OtherItemList item in Items.OtherItems)
            {
                if (item.AddTOList)
                {
                    if (item.Name == Resources.Global_String_ShippingTerms)
                    {
                        otherListItmz = new OtherSelectedListItems();
                        otherListItmz.ItemsList = new SelectList(taService.GetShippingTerms(countryProg.Id), "Id", "Description");
                        otherListItmz.ItemName = item.Name;
                        OtherLIstItems.Add(otherListItmz);
                    }
                    else if (item.Name == Resources.Global_String_PaymentTerms)
                    {
                        otherListItmz = new OtherSelectedListItems();
                        otherListItmz.ItemsList = new SelectList(taService.GetPaymentTerms(countryProg.Id), "Id", "Description");
                        otherListItmz.ItemName = item.Name;
                        OtherLIstItems.Add(otherListItmz);
                    }
                    else
                    {
                        OtherNoneList = new DisplayOtherSelectedItems();
                        OtherNoneList.ItemName = item.Name;
                        OtherNoneLIstItems.Add(OtherNoneList);
                    }
                }
            }
            model.OtherNoneListItems = OtherNoneLIstItems;
            model.OtherListItemsz = OtherLIstItems;
            model.TAid = Items.TAID;
            PopulateSupplierDetails(model);
            ViewBag.TAID = Items.TAID;
            model.IsSupplierSaved = isSaved;
            model.UserMessage = message;
            return View("GetSelectedItems", model);
        }

        private void PopulateSupplierDetails(Models.GetSelectedItems model)
        {
            model.ModelTA = new Models.TenderAnalysis();
            List<TenderBidder> TBList = taService.GetTenderBidderColl(model.TAid);
            List<Models.TenderItem> tenderItems = new List<TenderItem>();
            model.ModelTA.EntityTenderAnalysis = taService.GetTenderAnalysisEntity(model.TAid);
            Models.TenderItem tenderItem;
            List<TenderBidderQuote> tbQuotes;
            PopulateTALists(model.ModelTA, TBList);
            if (TBList.Count > 0)
            {
                model.ModelTA.HasSuppliers = true;
                tbQuotes = taService.GetTenderBidderQuoteColl(TBList[0].Id);
                foreach (TenderBidderQuote tbQuote in tbQuotes)
                {
                    tenderItem = new TenderItem();
                    tenderItem.UnitCost = new List<decimal>();
                    tenderItem.EntityRequestedItem = tbQuote.OrderRequestItem;
                    tenderItem.UnitCost.Add(tbQuote.UnitPrice * tbQuote.OrderRequestItem.Quantity);
                    tenderItems.Add(tenderItem);
                }
            }

            for (int i = 1; i < TBList.Count; i++)
            {
                tbQuotes = taService.GetTenderBidderQuoteColl(TBList[i].Id);
                for (int j = 0; j < tbQuotes.Count; j++)
                {
                    tenderItems[j].UnitCost.Add(tbQuotes[j].UnitPrice * tbQuotes[j].OrderRequestItem.Quantity);
                }
            }
            model.ModelTA.TBiderQuotes = tenderItems;
        }

        public ActionResult SubmitTender(Guid Id)
        {
            TenderAnalysi ta = taService.GetTenderAnalysisEntity(Id);
            ta.IsSubmitted = true;
            ta.IsRejected = false;
            ta.IsAuthorized = false;
            ta.RefNumber = taService.GenerateUniqueNumber(countryProg);
            taService.SaveTenderAnalysis(ta);
            TenderEvaluator evaluator = taService.GetTenderEvaluatorByPriority(Id, 1);
            string msgBody = string.Format(NotificationHelper.taMsgBody, evaluator.Staff.Person.FirstName);
            notificationService.SendNotification(evaluator.Staff.Person.OfficialEmail, msgBody, NotificationHelper.tasubject);
            return ViewTenders();
        }

        public ActionResult ViewTenders()
        {
            Models.ViewTenders tender;
            List<Models.ViewTenders> tenders = new List<Models.ViewTenders>();
            try
            {
                List<Model.TenderAnalysi> tenderlist = taService.GetTenderColl(countryProg.Id);
                foreach (TenderAnalysi item in tenderlist)
                {
                    tender = new ViewTenders();
                    tender.EntityTenderAnalysis = item;
                    tenders.Add(tender);
                }
                return View("ViewTenders", tenders);
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return View("ViewTenders", tenders);
            }
        }

        public ActionResult ViewTenderDetails(Guid id)
        {
            Models.TenderAnalysis modelTA = TAExtension.PrepareTAModel(id, taService);// new Models.TenderAnalysis();
            modelTA.CanEdit = modelTA.EntityTenderAnalysis.IsSubmitted != true && modelTA.EntityTenderAnalysis.IsRejected != true && modelTA.EntityTenderAnalysis.Staff1.Id == currentStaff.Id;
            ViewBag.Currency = modelTA.EntityTenderAnalysis.OrderRequest.Currency.ShortName;
            return View("ViewTenderDetails", modelTA);
        }

        private ActionResult PopulateTADetailsFrank(Guid id)
        {
            return GenerateTenderCrossTab(id);
        }

        private ActionResult GenerateTenderCrossTab(Guid id)
        {
            Models.TenderAnalysis modelTA = new Models.TenderAnalysis();
            modelTA.TenderAnalysisId = id;
            modelTA.HasSuppliers = false;
            List<TenderBidder> TBList = taService.GetTenderBidderColl(id);
            List<Models.TenderItem> tenderItems = new List<TenderItem>();
            modelTA.EntityTenderAnalysis = taService.GetTenderAnalysisEntity(id);
            Models.TenderItem tenderItem;
            List<TenderBidderQuote> tbQuotes;
            PopulateTALists(modelTA, TBList);
            if (TBList.Count > 0)
            {
                modelTA.HasSuppliers = true;
                tbQuotes = taService.GetTenderBidderQuoteColl(TBList[0].Id);
                foreach (TenderBidderQuote tbQuote in tbQuotes)
                {
                    tenderItem = new TenderItem();
                    tenderItem.UnitCost = new List<decimal>();
                    tenderItem.EntityRequestedItem = tbQuote.OrderRequestItem;
                    tenderItem.UnitCost.Add(tbQuote.UnitPrice);
                    tenderItems.Add(tenderItem);
                }
            }

            for (int i = 1; i < TBList.Count; i++)
            {
                tbQuotes = taService.GetTenderBidderQuoteColl(TBList[i].Id);
                for (int j = 0; j < tbQuotes.Count; j++)
                {
                    tenderItems[j].UnitCost.Add(tbQuotes[j].UnitPrice);
                }
            }
            modelTA.TBiderQuotes = tenderItems;
            ViewBag.TAID = id;
            return View("LoadTADetailzFrank", modelTA);
        }

        private void PopulateTALists(SCMS.UI.Models.TenderAnalysis ta, List<TenderBidder> tbList)
        {
            bool shipT, payT, warranty, delivTime, comments, transCost;
            shipT = payT = warranty = delivTime = comments = transCost = false;
            ta.SupplierName = new List<string>();
            ta.SupplierID = new List<Guid>();
            ta.ShippingTerm = new List<string>();
            ta.TermzOfPayment = new List<string>();
            ta.Warrant = new List<string>();
            ta.DeliveryTime = new List<DateTime>();
            ta.others = new List<string>();
            ta.TransportCost = new List<decimal>();
            ta.OtherID = new List<Guid>();
            ta.TenderBidderId = new List<Guid>();
            ta.TotalCost = new List<decimal>();

            foreach (TenderBidder tb in tbList)
            {
                ta.TenderBidderId.Add(tb.Id);
                ta.SupplierName.Add(tb.Supplier.Name);
                ta.SupplierID.Add(tb.SupplierId);
                if (tb.ShippingTermId != null)
                {
                    shipT = true;
                    ta.ShippingTerm.Add(tb.ShippingTerm.Name);
                }
                else
                    ta.ShippingTerm.Add(string.Empty);

                if (tb.PaymentTermId != null)
                {
                    payT = true;
                    ta.TermzOfPayment.Add(tb.PaymentTerm.Code);
                }
                else
                    ta.TermzOfPayment.Add(string.Empty);

                if (tb.Warranty != null)
                {
                    warranty = true;
                    ta.Warrant.Add(tb.Warranty);
                }
                else
                    ta.Warrant.Add(string.Empty);

                if (tb.DeliveryTime != null)
                {
                    delivTime = true;
                    ta.DeliveryTime.Add((DateTime)tb.DeliveryTime);
                }
                else
                    ta.DeliveryTime.Add(DateTime.MinValue);

                if (tb.Comments != null)
                {
                    comments = true;
                    ta.others.Add(tb.Comments);
                }
                else
                    ta.others.Add(string.Empty);

                if (tb.TransportCost != null)
                {
                    transCost = true;
                    ta.TransportCost.Add((decimal)tb.TransportCost);
                }
                else
                    ta.TransportCost.Add(0);
                ta.OtherID.Add(tb.Id);
                ta.TotalCost.Add((decimal)tb.TotalCost);
            }

            //Clear lists that have nothing completely
            if (!shipT) ta.ShippingTerm.Clear();
            if (!payT) ta.TermzOfPayment.Clear();
            if (!warranty) ta.Warrant.Clear();
            if (!delivTime) ta.DeliveryTime.Clear();
            if (!comments) ta.others.Clear();
            if (!transCost) ta.TransportCost.Clear();
        }

        public ActionResult BackToAddSuppliers(Guid id)
        {
            try
            {
                return GettselectedIttems(UserSession.CurrentSession.SSItems, true);
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return View("SelectEvaluators");
            }
        }

        public ActionResult SelectEvaluators(Guid id)
        {
            try
            {
                return GetEvaluators(id);
            }
            catch (Exception ex)
            {
                return GettselectedIttems(UserSession.CurrentSession.SSItems, true, ex.Message);
            }
        }

        public ActionResult LoadAddEvaluator(Guid id)
        {
            List<TenderEvaluator> evaluators = taService.GetTenderEvaluators(id);
            List<ApprovalLevel> evalLevels = new List<ApprovalLevel>();
            for (int i = 1; i <= 3; i++)
            {
                if (!PriorityAlreadySet(i, evaluators))
                    evalLevels.Add(new ApprovalLevel { Level = i });
            }

            SelectEvaluators evaluator = new Models.SelectEvaluators()
            {
                EntityTenderEvaluator = new TenderEvaluator(),
                Staffs = new SelectList(taService.GetStaffForTAEvaluation(countryProg.Id, id), "Id", "StaffName"),
                ApprovalLevels = new SelectList(evalLevels, "Level", "Level"),
                Approvers = evaluators
            };
            ViewBag.TAID = id;

            return View("AddEvaluator", evaluator);
        }

        private ActionResult GetEvaluators(Guid id, string message = "", int status = 0)
        {
            List<TenderEvaluator> evaluators = taService.GetTenderEvaluators(id);
            List<ApprovalLevel> evalLevels = new List<ApprovalLevel>();
            for (int i = 1; i <= 3; i++)
            {
                if (!PriorityAlreadySet(i, evaluators))
                    evalLevels.Add(new ApprovalLevel { Level = i });
            }

            SelectEvaluators evaluator = new Models.SelectEvaluators()
            {
                EntityTenderEvaluator = new TenderEvaluator(),
                Staffs = new SelectList(taService.GetStaffForTAEvaluation(countryProg.Id, id), "Id", "StaffName"),
                ApprovalLevels = new SelectList(evalLevels, "Level", "Level"),
                UserMessage = message,
                status = status,
                Approvers = evaluators
            };
            ViewBag.TAID = id;

            return View("SelectEvaluators", evaluator);
        }

        private bool PriorityAlreadySet(int priority, List<TenderEvaluator> evaluators)
        {
            foreach (var evaluator in evaluators)
            {
                if (priority == evaluator.Priority)
                    return true;
            }
            return false;
        }

        public ActionResult ChangeEvaluator(Guid id)
        {
            Guid tenderId = new Guid();
            try
            {
                TenderEvaluator entityEval = taService.GetTenderEvaluatorById(id);
                tenderId = (Guid)entityEval.TenderAnalysisId;
                List<TenderEvaluator> evaluators = taService.GetTenderEvaluators(tenderId);
                List<ApprovalLevel> evalLevels = new List<ApprovalLevel>();
                for (int i = 1; i <= 2; i++)
                {
                    if (entityEval.Priority == i || !PriorityAlreadySet(i, evaluators))
                        evalLevels.Add(new ApprovalLevel { Level = i });
                }

                SelectEvaluators evaluator = new Models.SelectEvaluators()
                {
                    EntityTenderEvaluator = entityEval,
                    Staffs = new SelectList(taService.GetStaffForTAEvaluation(countryProg.Id, tenderId, (Guid)entityEval.StaffId), "Id", "StaffName", entityEval.StaffId),
                    ApprovalLevels = new SelectList(evalLevels, "Level", "Level", entityEval.Priority),
                    UserMessage = "",
                    status = 0,
                    Approvers = evaluators
                };
                ViewBag.TAID = tenderId;
                return View("AddEvaluator", evaluator);
            }
            catch (Exception ex)
            {
                return GetEvaluators(tenderId, ex.Message);
            }
        }

        public ActionResult SaveEvaluator(Guid id, SelectEvaluators entity)
        {
            try
            {
                entity.EntityTenderEvaluator.TenderAnalysisId = id;
                entity.EntityTenderEvaluator.Priority = entity.Priority;
                if (taService.SaveEvaluators(entity.EntityTenderEvaluator))
                    return GetEvaluators((Guid)entity.EntityTenderEvaluator.TenderAnalysisId, Resources.TenderAnalysisController_String_EvaluatorSaved, 1);
                else
                    return GetEvaluators((Guid)entity.EntityTenderEvaluator.TenderAnalysisId, Resources.Global_String_AnErrorOccurred);
            }
            catch (Exception ex)
            {
                return GetEvaluators(id, ex.Message);
            }
        }

        public ActionResult ChangeAuthorizer(Guid id)
        {
            try
            {
                SelectAuthorizer model = new SelectAuthorizer()
                    {
                        EntityTenderEvaluator = taService.GetTenderEvaluatorById(id),
                        Authorizers = new SelectList(staffService.GetApproversByDocumentType(NotificationHelper.taCode, NotificationHelper.authorizationCode, countryProg.Id), "Id", "StaffName")
                    };
                return View(model);

            }
            catch (Exception ex)
            {
                return GetEvaluators(id, ex.Message);
            }
        }

        public ActionResult DeleteEvaluator(Guid id)
        {
            Guid taId = Guid.Empty;
            try
            {
                TenderEvaluator entityEval = taService.GetTenderEvaluatorById(id);
                taId = (Guid)entityEval.TenderAnalysisId;
                taService.DeleteTenderEvaluator(entityEval.Id);
                return GetEvaluators(taId, Resources.TenderAnalysisController_String_EvaluatorRemoved);
            }
            catch (Exception ex)
            {
                return GetEvaluators(taId, Resources.Global_String_AnErrorOccurred);
            }
        }
        
        public ActionResult Search()
        {
            var model = new SearchTA()
            {
                EntityTA = new TenderAnalysi()
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Search(SearchTA entity)
        {
            Models.ViewTenders tender;
            List<Models.ViewTenders> tenders = new List<Models.ViewTenders>();
            try
            {
                List<Model.TenderAnalysi> items = taService.Search(entity.EntityTA);
                foreach (TenderAnalysi item in items)
                {
                    tender = new ViewTenders();
                    tender.EntityTenderAnalysis = item;
                    tenders.Add(tender);
                }

                return View("ViewTenders", tenders);
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return View("ViewTenders", tenders);
            }
        }

        public ActionResult DeleteTA(Guid id)
        {
            taService.DeleteTenderAnalysis(id);
            return ViewTenders();
        }

        public ActionResult EditTA(Guid id)
        {
            TenderAnalysi ta = taService.GetTenderAnalysisEntity(id);
            List<TenderBidder> TBList = taService.GetTenderBidderColl(id);
            TAORequest tanalysis = new Models.TAORequest()
            {
                EntityTenderAnalysis = ta,
                OrderRequests = new SelectList(taService.GetOrderRequests(countryProg.Id, ta.OrderRequestId.ToString()), "Id", "RefNumber", ta.OrderRequestId),
                TenderAnalisysNo = ta.RefNumber,
                TADate = ta.AnalysisDate,
                EditMode = true,
                SupplierAdded = TBList.Count > 0
            };
            StoreTASession(ta, TBList);
            return View("LoadORDetails", tanalysis);
        }

        private void StoreTASession(TenderAnalysi ta, List<TenderBidder> TBList)
        {
            SelectItemsToConsider taItems = new SelectItemsToConsider();
            taItems.TAID = ta.Id;
            if (TBList.Count == 0)
                return;
            List<TenderBidderQuote> TBQList = taService.GetTenderBidderQuoteColl(TBList[0].Id);
            List<ORItemList> orItems = new List<ORItemList>();
            foreach (TenderBidderQuote tbq in TBQList)
            {
                orItems.Add(new ORItemList { EntityORItem = tbq.OrderRequestItem, AddToList = true });
            }
            List<OtherItemList> otherItems = new List<OtherItemList>();
            InitOtherItemsList(otherItems);
            InitOtherItemsList(otherItems, TBList[0]);
            taItems.EntityORItems = orItems;
            taItems.OtherItems = otherItems;
            UserSession.CurrentSession.SSItems = taItems;
        }

        #endregion

        #region .Add New Supplier.
        
        public ActionResult AddNewSupplier4TA(Guid id)
        {
            SelectItemsToConsider Items = UserSession.CurrentSession.SSItems;
            USupplier supplier = new USupplier();
            ViewBag.TAID = id;
            return View("AddNewSupplier4TA", supplier);
        }

        [HttpPost]
        public ActionResult AddNewSupplier4TA(USupplier model, Guid id)
        {
            SelectItemsToConsider Items = UserSession.CurrentSession.SSItems;
            Supplier supplier = null;
            supplier = supplierService.GetSupplierByName(model.Name, countryProg.Id);
            if (supplier == null)
            {
                supplier = new Supplier();
                supplier.Name = model.Name;
                supplier.Address = model.Address != null && model.Address.Trim().Length > 0 ? model.Address : Resources.SystemUser_ViewProfile_NotSet.ToUpper();
                supplier.PrimaryPhone = model.PrimaryPhone != null && model.PrimaryPhone.Trim().Length > 0 ? model.PrimaryPhone : Resources.SystemUser_ViewProfile_NotSet.ToUpper();
                supplier.CountryId = countryProg.CountryId;
                supplier.CountryProgrammeId = countryProg.Id;
                supplier.IsApproved = false;
                supplierService.AddSupplier(supplier);
            }
            return LoadAddSupplier(id, supplier.Id);
        }

        #endregion
    }
}
